<template>
  <div class="app-container">
    <el-form :model="searchForm" :inline="true">
      <el-row>
        <el-col :span="20">
          <el-form-item>
            <el-input v-model="searchForm.fuzzy" style="width:200px" placeholder="设备编号/名称" clearable @keyup.enter.native="handleSearch" />
          </el-form-item>
          <el-form-item>
            <el-select v-model="searchForm.deviceClass" clearable style="width:150px" filterable placeholder="设备类别">
              <el-option value="1" label="温湿度计">温湿度计</el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <treeselect
              style="width:150px"
              v-model="positionFind"
              :options="locationArray"
              :normalizer="normalizerTwo"
              placeholder="监测位置"/>
          </el-form-item>
          <el-form-item>
            <el-select v-model="searchForm.deviceStatus" clearable style="width:150px" filterable placeholder="设备状态">
              <el-option value="0" label="在线">在线</el-option>
              <el-option value="2" label="停用">停用</el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" class="iconfont icon-chaxun1" @click="handleSearch"> 查询</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="4" class="search-right">
          <el-button type="text" icon="el-icon-plus" @click="createDevice">新增设备</el-button>
          <el-button type="text" icon="el-icon-refresh" @click="handleSearch">刷新</el-button>
        </el-col>
      </el-row>
    </el-form>
    <el-table
      border
      :data="ambientData"
      stripe
      highlight-current-row
      :header-cell-style="{background:'#ECF3FC'}"
    >
      <el-table-column type="index" width="50" label="序号" align="center" />
      <el-table-column prop="deviceCode" label="设备编号" width="160px" align="center" />
      <el-table-column prop="deviceName" label="设备名称" width="160px" align="center" />
      <el-table-column prop="deviceClass" label="设备类别" align="center">
        <template slot-scope="{row}">
          <span v-if="row.deviceClass === '1'">温湿度计</span>
        </template>
      </el-table-column>
      <el-table-column prop="monitorLocationName" label="监测位置" width="140px" align="center" />
      <el-table-column prop="instrumentModel" label="设备型号" width="140px" align="center" />
      <el-table-column prop="instrumentBrand" label="设备品牌" width="140px" align="center" />
      <el-table-column prop="factoryNo" label="出厂编号" width="160px" align="center" />
      <el-table-column prop="createTime" label="创建日期" width="160" align="center" />
      <el-table-column prop="liableUserId" label="责任人" align="center" />
      <el-table-column prop="deviceStatus" label="设备状态" width="120px" align="center">
        <template slot-scope="{row}">
          <span v-if="row.deviceStatus === '0'"><el-button type="text" style="color: #fff;cursor: default;background-color: rgb(19, 206, 102);padding-left: 10px;padding-right: 10px;">在线</el-button></span>
          <span v-if="row.deviceStatus === '2'"><el-button type="text" style="color: #fff;cursor: default;background-color: rgba(73,69,64,0.65);padding-left: 10px;padding-right: 10px;">停用</el-button></span>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" width="160" align="center">
        <template slot-scope="row">
          <el-popover placement="top-start" width="200" trigger="hover" :content="row.row.remark">
            <p class="table2" slot="reference">
              {{ row.row.remark}}
            </p>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" align="center" width="230px">
        <template slot-scope="{row}">
          <el-button type="text" @click="seeAmbient(row)">查看</el-button>
          <el-button type="text" @click="updateAmbient(row)">修改</el-button>
          <el-button type="text" v-if="row.deviceStatus === '0'" @click="enableOrStopAmbientsDevice(row.id, row.deviceStatus)">停用</el-button>
          <el-button type="text" v-if="row.deviceStatus === '2'" @click="enableOrStopAmbientsDevice(row.id, row.deviceStatus)">启用</el-button>
          <el-button type="text" @click="copyAmbientsDevice(row.id)">复制</el-button>
          <el-button type="text" @click="deleteAmbientsDevice(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="float: right">
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="searchForm.pageNumber"
        :limit.sync="searchForm.pageSize"
        @pagination="handleSearch"/>
    </div>

    <!-- 新增环境设备 -->
    <el-dialog title="新增环境设备" :visible.sync="addAmbientVisible" center width="50%" :close-on-click-modal="false">
      <div>
        <el-form ref="ambientForm" :model="ambientForm" :rules="ambientRules" label-width="120px">
          <el-row>
            <el-col :span="11">
              <el-form-item prop="deviceName" label="设备名称:">
                <el-input v-model="ambientForm.deviceName" />
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item prop="instrumentModel" label="设备型号:">
                <el-input v-model="ambientForm.instrumentModel" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item prop="deviceClass" label="设备类别:">
                <el-select v-model="ambientForm.deviceClass" clearable placeholder="设备类别" style="width: 185px;">
                  <el-option value="1" label="温湿度计">温湿度计</el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item prop="factoryNo" label="出厂编号:">
                <el-input v-model="ambientForm.factoryNo" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item prop="instrumentBrand" label="设备品牌:">
                <el-input v-model="ambientForm.instrumentBrand" />
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item  prop="monitorLocation" label="监测位置:">
                <treeselect
                  style="width:185px"
                  v-model="positionAdd"
                  :options="locationArray"
                  :normalizer="normalizerTwo"
                  placeholder="监测位置"
                  @select="changeSelect"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item prop="liableUserId" label="责任人:">
                <el-input v-model="ambientForm.liableUserId" />
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item  prop="involvedUserIds" label="授权使用人:">
                <el-input v-model="userName" :readonly="true"/>
              </el-form-item>
            </el-col>
            <el-button type="text" @click="addInvolvedUserId">&nbsp;选择</el-button>
          </el-row>
          <el-row>
            <el-col :span="22">
              <el-form-item prop="remark" label="备注:">
                <el-input type="textarea" v-model="ambientForm.remark" :rows="3" maxlength="300" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer" style="margin-top: -30px;float: right;">
        <el-button @click="addAmbientVisible=false">取消</el-button>
        <el-button type="primary" @click="saveAmbient">确认</el-button>
      </div>
    </el-dialog>

    <!-- 查看环境设备 -->
    <el-dialog title="环境设备详情" :visible.sync="seeAmbientVisible" center width="50%" :close-on-click-modal="false">
      <div>
        <el-form :model="seeAmbientForm" label-width="120px">
          <el-row>
            <el-col :span="11">
              <el-form-item prop="deviceName" label="设备名称:">
                <el-input v-model="seeAmbientForm.deviceName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item prop="instrumentModel" label="设备型号:">
                <el-input v-model="seeAmbientForm.instrumentModel" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item prop="deviceClass" label="设备类别:">
                <el-select v-model="seeAmbientForm.deviceClass" clearable placeholder="设备类别" disabled style="width: 185px;">
                  <el-option value="1" label="温湿度计">温湿度计</el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item prop="factoryNo" label="出厂编号:">
                <el-input v-model="seeAmbientForm.factoryNo" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item prop="instrumentBrand" label="设备品牌:">
                <el-input v-model="seeAmbientForm.instrumentBrand" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item  prop="monitorLocation" label="监测位置:">
                <treeselect
                  style="width:185px"
                  v-model="positionSee"
                  :options="locationArray"
                  :normalizer="normalizerTwo"
                  placeholder="监测位置"
                  disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item prop="liableUserId" label="责任人:">
                <el-input v-model="seeAmbientForm.liableUserId" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item  prop="involvedUserIds" label="授权使用人:">
                <el-select v-model="seeAmbientForm.involvedUserIds" multiple clearable placeholder="授权使用人" @change="getsUserId" disabled>
                  <el-option
                    v-for="item in userIdArray"
                    :key="item.userId"
                    :label="item.empName"
                    :value="item.userId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="22">
              <el-form-item prop="remark" label="备注:">
                <el-input type="textarea" v-model="seeAmbientForm.remark" :rows="3" maxlength="300" disabled />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer" style="margin-top: -30px;float: right;">
        <el-button @click="seeAmbientVisible=false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 修改环境设备 -->
    <el-dialog title="修改环境设备" :visible.sync="updateAmbientVisible" center width="50%" :close-on-click-modal="false">
      <div>
        <el-form ref="updateAmbientForm" :model="updateAmbientForm" :rules="updateAmbientRules" label-width="120px">
          <el-row>
            <el-col :span="11">
              <el-form-item prop="deviceCode" label="设备编号:">
                <el-input v-model="updateAmbientForm.deviceCode" />
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item prop="deviceName" label="设备名称:">
                <el-input v-model="updateAmbientForm.deviceName" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item prop="instrumentModel" label="设备型号:">
                <el-input v-model="updateAmbientForm.instrumentModel" />
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item prop="deviceClass" label="设备类别:">
                <el-select v-model="updateAmbientForm.deviceClass" clearable placeholder="设备类别" style="width: 185px;">
                  <el-option value="1" label="温湿度计">温湿度计</el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item prop="factoryNo" label="出厂编号:">
                <el-input v-model="updateAmbientForm.factoryNo" />
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item prop="instrumentBrand" label="设备品牌:">
                <el-input v-model="updateAmbientForm.instrumentBrand" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item  prop="monitorLocation" label="监测位置:">
                <treeselect
                  style="width:185px"
                  v-model="positionUpdate"
                  :options="locationArray"
                  :normalizer="normalizerTwo"
                  placeholder="监测位置"
                  @select="changeSelectUpdate"/>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item prop="liableUserId" label="责任人:">
                <el-input v-model="updateAmbientForm.liableUserId" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item  prop="involvedUserIds" label="授权使用人:">
                <el-input v-model="updateUserName" :readonly="true"/>
              </el-form-item>
            </el-col>
            <el-button type="text" @click="updateInvolvedUserId">&nbsp;选择</el-button>
            <el-col :span="22">
              <el-form-item prop="remark" label="备注:">
                <el-input type="textarea" v-model="updateAmbientForm.remark" :rows="3" maxlength="300" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer" style="margin-top: -30px;float: right;">
        <el-button @click="updateAmbientVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmAmbient">确认</el-button>
      </div>
    </el-dialog>

    <!-- 添加授权使用人 -->
    <el-dialog title="添加授权使用人" :visible.sync="addInvolvedUserIdVisible" center width="1000px" :close-on-click-modal="false">
        <el-form :inline="true">
          <el-row>
              <el-form-item>
                <div style="height: 560px;overflow: auto;overflow-x: hidden;">
                  <div class="head-container">
                    <el-input
                      v-model="deptsName"
                      placeholder="请输入部门名称"
                      clearable
                      size="small"
                      prefix-icon="el-icon-search"
                      style="margin-bottom: 20px;"
                    />
                  </div>
                  <div class="head-container">
                    <el-tree
                      ref="tree"
                      :data="deptOptions"
                      :props="defaultPropsDept"
                      :expand-on-click-node="false"
                      :filter-node-method="filterNodeDept"
                      default-expand-all
                      @node-click="handleNodeClickDept"
                    />
                  </div>
                </div>
              </el-form-item>
          </el-row>
        </el-form>
        <div class="container2">
          <tree-transfer
            ref="treeTransfer"
            :title="titles"
            :from_data="fromData"
            :to_data="toData"
            :mode="mode"
            :pid="parentId"
            :defaultProps="{ label: 'label', children: 'children' }"
            :style="{ height: '75%'}"
            defaultTransfer
            filter
            :filter-node="filterNode">
          </tree-transfer>
        </div>
      <div style="margin-top: -97px;text-align: center;">
        <el-button @click="addInvolvedUserIdVisible=false">取消</el-button>
        <el-button type="primary" @click="saveInvolvedUserId" :disabled="toData.length === 0">保存</el-button>
      </div>
    </el-dialog>

    <!-- 修改授权使用人 -->
    <el-dialog title="修改授权使用人" :visible.sync="updateInvolvedUserIdVisible" center width="1000px" :close-on-click-modal="false">
      <el-form :inline="true">
        <el-row>
          <el-form-item>
            <div style="height: 560px;overflow: auto;overflow-x: hidden;">
              <div class="head-container">
                <el-input
                  v-model="deptsName"
                  placeholder="请输入部门名称"
                  clearable
                  size="small"
                  prefix-icon="el-icon-search"
                  style="margin-bottom: 20px;"
                />
              </div>
              <div class="head-container">
                <el-tree
                  ref="tree"
                  :data="deptOptions"
                  :props="defaultPropsDept"
                  :expand-on-click-node="false"
                  :filter-node-method="filterNodeDept"
                  default-expand-all
                  @node-click="handleNodeClickDept"
                />
              </div>
            </div>
          </el-form-item>
        </el-row>
      </el-form>
      <div class="container2">
        <tree-transfer
          ref="treeTransfer"
          :title="titles"
          :from_data="fromData"
          :to_data="toData"
          :mode="mode"
          :pid="parentId"
          :defaultProps="{ label: 'label', children: 'children' }"
          :style="{ height: '75%'}"
          defaultTransfer
          filter
          :filter-node="filterNode">
        </tree-transfer>
      </div>
      <div style="margin-top: -97px;text-align: center;">
        <el-button @click="updateInvolvedUserIdVisible=false">取消</el-button>
        <el-button type="primary" @click="saveUpdateInvolvedUserId" :disabled="toData.length === 0">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import * as ambientServer from '@/api/ambient'
import * as instrServer from '@/api/instrument'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import treeTransfer from "el-tree-transfer";
import * as deptServer from '@/api/dept'

export default {
  components: { Pagination, Treeselect, treeTransfer },
  data() {
    return {
      searchForm: {
        fuzzy: '',
        deviceCode: '',
        deviceName: '',
        deviceClass: '',
        monitorLocation: '',
        deviceStatus: '',
        pageNumber: 1,
        pageSize: 10
      },
      total: 0,
      ambientData: [],
      locationArray: [],
      userIdArray: [],
      addAmbientVisible: false,
      ambientForm: {
        deviceName: '',
        instrumentModel: '',
        deviceClass: '',
        factoryNo: '',
        instrumentBrand: '',
        monitorLocation: '',
        liableUserId: '',
        involvedUserIds: '',
        remark: ''
      },
      ambientRules: {
        deviceName: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
        instrumentModel: [{ required: true, message: '请输入设备型号', trigger: 'blur' }],
        deviceClass: [{ required: true, message: '请选择设备类别', trigger: 'blur' }],
        factoryNo: [{ required: true, message: '请输入出厂编号', trigger: 'blur' }],
        monitorLocation: [{ required: true, message: '请选择监测位置', trigger: 'blur' }],
        liableUserId: [{ required: true, message: '请输入责任人', trigger: 'blur' }],
        involvedUserIds: [{ required: true, message: '请选择授权使用人', trigger: 'blur' }]
      },
      seeAmbientVisible: false,
      seeAmbientForm: {
        deviceName: '',
        instrumentModel: '',
        deviceClass: '',
        factoryNo: '',
        instrumentBrand: '',
        monitorLocation: '',
        liableUserId: '',
        involvedUserIds: '',
        remark: ''
      },
      updateAmbientVisible: false,
      updateAmbientForm: {
        ambientDeviceId: null,
        deviceCode: '',
        deviceName: '',
        instrumentModel: '',
        deviceClass: '',
        factoryNo: '',
        instrumentBrand: '',
        monitorLocation: '',
        liableUserId: '',
        involvedUserIds: '',
        remark: ''
      },
      updateAmbientRules: {
        deviceCode: [{ required: true, message: '请输入设备编号', trigger: 'blur' }],
        deviceName: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
        instrumentModel: [{ required: true, message: '请输入设备型号', trigger: 'blur' }],
        deviceClass: [{ required: true, message: '请选择设备类别', trigger: 'blur' }],
        factoryNo: [{ required: true, message: '请输入出厂编号', trigger: 'blur' }],
        monitorLocation: [{ required: true, message: '请选择监测位置', trigger: 'blur' }],
        liableUserId: [{ required: true, message: '请输入责任人', trigger: 'blur' }],
        involvedUserIds: [{ required: true, message: '请选择授权使用人', trigger: 'blur' }]
      },
      positionFind: null,
      positionAdd: null,
      positionSee: null,
      positionUpdate: null,

      parentId: "parentId",
      mode: "transfer",
      titles: ["待选人员", "已选人员"],
      toData: [], //选中的数据
      fromData: [], //根据部门ids查询出的数据结构
      deptPulldownArray: [],
      nodeLableArray: [],
      addInvolvedUserIdVisible: false,
      userName: '',
      deptsName: null,  // 部门名称
      deptOptions: null,   // 部门树选项
      defaultPropsDept: { children: "children", label: "label", id: "id" },
      deptId: null,
      updateInvolvedUserIdVisible: false,
      updateUserName: '',
    }
  },
  watch: {
    // 根据名称筛选部门树
    deptsName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.handleSearch()
    this.getsLocation()
    this.getsUserId()
    this.findDeptPulldown()
    this.getTreeselectDept();
  },
  methods: {
    handleSearch() {
      this.searchForm.monitorLocation = this.positionFind
      ambientServer.findAmbientsDevice(this.searchForm).then(res => {
        if (res.code === 200 && res.result) {
          this.ambientData = res.result.records || []
          this.total = res.result.total
        }
      })
    },

    // 监测位置列表
    getsLocation() {
      instrServer.roomList().then(res => {
        this.locationArray = res.result;
      });
    },

    // 转换数据结构
    normalizerTwo(node) {
      if (node.childList && !node.childList.length) {
        delete node.childList;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.childList
      };
    },

    changeSelect(e) {
      this.ambientForm.monitorLocation = e.id;
    },

    changeSelectUpdate(e) {
      this.updateAmbientForm.monitorLocation = e.id;
    },

    // 仪器授权使用人下拉
    getsUserId() {
      ambientServer.findUserList().then(res => {
        this.userIdArray = res.result || []
      })
    },

    // 新增环境设备
    createDevice() {
      this.positionAdd = null
      this.ambientForm = {
        deviceName: '',
        instrumentModel: '',
        deviceClass: '',
        factoryNo: '',
        instrumentBrand: '',
        monitorLocation: '',
        liableUserId: '',
        involvedUserIds: '',
        remark: ''
      };
      this.userName = ''
      this.toData = []
      this.addAmbientVisible = true
    },

    // 保存环境设备
    saveAmbient() {
      this.ambientForm.monitorLocation = this.positionAdd
      this.$refs.ambientForm.validate(valid => {
        if (valid) {
          ambientServer.addAmbientDevice(this.ambientForm).then(res => {
            if (res.code === 200) {
              this.$notify({
                title: '成功',
                message: res.message,
                type: 'success'
              })
              this.addAmbientVisible = false;
              this.ambientForm = {
                deviceName: '',
                instrumentModel: '',
                deviceClass: '',
                factoryNo: '',
                instrumentBrand: '',
                monitorLocation: '',
                liableUserId: '',
                involvedUserIds: '',
                remark: ''
              };
              this.userName = ''
              this.toData = []
              this.handleSearch();
            } else {
              this.$notify({
                title: '失败',
                message: res.message,
                type: 'error'
              })
            }
          })
        }
      })
    },

    // 查看
    seeAmbient(row) {
      this.positionSee = row.monitorLocation
      this.seeAmbientForm.deviceName = row.deviceName
      this.seeAmbientForm.instrumentModel = row.instrumentModel
      this.seeAmbientForm.deviceClass = row.deviceClass
      this.seeAmbientForm.factoryNo = row.factoryNo
      this.seeAmbientForm.instrumentBrand = row.instrumentBrand
      this.seeAmbientForm.liableUserId = row.liableUserId
      this.seeAmbientForm.involvedUserIds = row.involvedUserId.split(',')
      this.seeAmbientForm.remark = row.remark
      this.seeAmbientVisible = true
    },

    // 启用、停用环境设备
    enableOrStopAmbientsDevice(ambientDeviceId, deviceStatus) {
      let startOrStop = "";
      let deviceSlant = "0";
      if (deviceStatus === '0'){
        startOrStop = "停用";
        deviceSlant = "2";
      }else if (deviceStatus === '2'){
        startOrStop = "启用";
        deviceSlant = "0";
      }
      this.$confirm("确定" + startOrStop + "吗?", '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = { ambientDeviceId: ambientDeviceId, deviceStatus: deviceSlant };
        ambientServer.enableOrStopsAmbientDevice(data).then(result => {
          if (result.code === 200) {
            this.$notify({
              title: '成功',
              message: result.message,
              type: 'success'
            })
            this.handleSearch()
          } else {
            this.$notify({
              title: '失败',
              message: result.message,
              type: 'error'
            })
          }
        })
      }).catch(() => {})
    },

    // 修改环境设备
    updateAmbient(row) {
      this.updateUserName = ''
      this.fromData = []
      this.toData = []
      let rowToData = JSON.parse(JSON.stringify(row.toData))
      this.toData = rowToData
      var updateUNames = []
      this.toData.forEach(item => {
        updateUNames.push(item.label)
      })
      this.updateUserName = updateUNames.join('，');

      this.positionUpdate = row.monitorLocation
      this.updateAmbientForm.ambientDeviceId = row.id
      this.updateAmbientForm.deviceCode = row.deviceCode
      this.updateAmbientForm.deviceName = row.deviceName
      this.updateAmbientForm.instrumentModel = row.instrumentModel
      this.updateAmbientForm.deviceClass = row.deviceClass
      this.updateAmbientForm.factoryNo = row.factoryNo
      this.updateAmbientForm.instrumentBrand = row.instrumentBrand
      this.updateAmbientForm.liableUserId = row.liableUserId
      this.updateAmbientForm.involvedUserIds = row.involvedUserId.split(',')
      this.updateAmbientForm.remark = row.remark
      this.updateAmbientVisible = true
    },

    // 保存--已修改的环境设备
    confirmAmbient() {
      this.updateAmbientForm.monitorLocation = this.positionUpdate
      this.$refs.updateAmbientForm.validate(valid => {
        if (valid) {
          ambientServer.updateAmbientsDevice(this.updateAmbientForm).then(res => {
            if (res.code === 200) {
              this.$notify({
                title: '成功',
                message: res.message,
                type: 'success'
              })
              this.updateAmbientVisible = false;
              this.handleSearch();
            } else {
              this.$notify({
                title: '失败',
                message: res.message,
                type: 'error'
              })
            }
          })
        }
      })
    },

    // 复制环境设备
    copyAmbientsDevice(ambientDeviceId) {
      this.$confirm("确定复制吗?", '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = { ambientDeviceId: ambientDeviceId };
        ambientServer.copysAmbientDevice(data).then(result => {
          if (result.code === 200) {
            this.$notify({
              title: '成功',
              message: result.message,
              type: 'success'
            })
            this.handleSearch()
          } else {
            this.$notify({
              title: '失败',
              message: result.message,
              type: 'error'
            })
          }
        })
      }).catch(() => {})
    },

    // 删除环境设备
    deleteAmbientsDevice(ambientDeviceId) {
      this.$confirm("确定删除吗?", '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = { ambientDeviceId: ambientDeviceId };
        ambientServer.deletesAmbientDevice(data).then(result => {
          if (result.code === 200) {
            this.$notify({
              title: '成功',
              message: result.message,
              type: 'success'
            })
            this.handleSearch()
          } else {
            this.$notify({
              title: '失败',
              message: result.message,
              type: 'error'
            })
          }
        })
      }).catch(() => {})
    },


    // 部门下拉数据
    findDeptPulldown() {
      ambientServer.findDeptPulldownData().then(res => {
        this.deptPulldownArray = res.result;
      });
    },

    // el-input的change事件移除焦点触发,此处用于给授权使用人赋值
    handlerInvolvedUserId() {
      var userIds = [];
      this.toData.forEach(item => {
        userIds.push(item.id)
      })
      this.ambientForm.involvedUserIds = userIds;
    },

    // 添加授权使用人
    addInvolvedUserId() {
      this.fromData = []
      this.addInvolvedUserIdVisible = true
    },

    // 保存授权使用人
    saveInvolvedUserId() {
      var userNames = [];
      this.toData.forEach(item => {
        userNames.push(item.label)
      })
      this.userName = userNames.join('，');
      this.handlerInvolvedUserId();
      this.addInvolvedUserIdVisible = false
    },

    // 根据选中的部门ids查询下面所有的员工信息
    deptSearch() {
      ambientServer.findUserByDeptId(this.deptId).then(res => {
        this.fromData = []
        if (res.code === 200 && res.result) {
          this.fromData = res.result || []

          if (this.toData.length > 0) {
            // 已选数据
            var arr2 = [];
            this.toData.forEach(item => {
              arr2.push(item.id)
            })
            // 待选数据
            var arr3 = [];
            this.fromData.forEach(item => {
              arr3.push(item.id)
            })
            // 已、待选数据交集
            var arr4 = [];
            arr3.forEach(val => {
              if (arr2.indexOf(val) < 0) {
                arr4.push(val);
              } else {
                arr2.splice(arr2.indexOf(val), 1);
              }
            });
            // 筛选后待选数据
            var arr5 = [];
            var sedata = arr4.concat(arr2);
            this.fromData.forEach(item => {
              if (sedata.includes(item.id)) {
                arr5.push({ id: item.id, label: item.label })
              }
            })
            this.fromData = arr5
          }

        }
      })
    },

    // 穿梭框模糊查询
    filterNode(value, data) {
      if (!value) return true;
      return data["label"] ? data["label"].indexOf(value) !== -1 : false;
    },

    // 部门模糊查询
    filterNodeDept(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },

    // 节点单击事件
    handleNodeClickDept(data) {
      if (data.parentId !== "0") {
        this.deptId = data.id;
      } else {
        this.deptId = "";
      }
      this.deptSearch();
    },

    // 查询部门下拉树结构
    getTreeselectDept() {
      this.deptOptions = [];
      deptServer.treeselect().then(res => {
        this.deptOptions = this.doProceDept(res.result) || [];
      });
    },

    // 装配数据结构
    doProceDept(depts) {
      const res = [];
      depts.forEach(e => {
        const tmp = { ...e };
        if (tmp.children && tmp.children.length > 0) {
          tmp.children = this.doProceDept(tmp.children);
        } else {
          tmp.children = undefined;
        }
        res.push(tmp);
      });
      return res;
    },

    // 修改授权使用人
    updateInvolvedUserId() {
      this.updateInvolvedUserIdVisible = true
    },

    // 保存修改授权使用人
    saveUpdateInvolvedUserId() {
      var userNames = [];
      this.toData.forEach(item => {
        userNames.push(item.label)
      })
      this.updateUserName = userNames.join('，');
      this.handlerUpdateInvolvedUserId();
      this.updateInvolvedUserIdVisible = false
    },

    // el-input的change事件移除焦点触发,此处用于给授权使用人赋值（修改使用）
    handlerUpdateInvolvedUserId() {
      var userIds = [];
      this.toData.forEach(item => {
        userIds.push(item.id)
      })
      this.updateAmbientForm.involvedUserIds = userIds;
    },

  }
}
</script>

<style scoped lang="scss" type="text/scss">
.search_div {
  >div {
    &:nth-child(1){
      margin-right: 10px;
    }
    display: inline-block;
  }
}
.search_input {
  width: 200px;
  margin-bottom: 5px;
}
.search-right {
  text-align: right;
  padding-right: 25px;
}
.item {
  font-size: 16px;
}
::v-deep .el-card .el-card__header {
  padding: 5px 20px;
  background: #F3F2F2;
}
.apostrophe{
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}
.table2  {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
}
/deep/ .vue-treeselect--disabled .vue-treeselect__single-value{
  color: #909399
}

.container2 {
  width: 680px;
  height: 620px;
  overflow: auto;
  overflow-x: hidden;
  margin-left: 250px;
  margin-top: -525px;
}
/deep/ .wl-transfer .transfer-main {
  padding: 10px;
  height: calc(100% - 80px);
  box-sizing: border-box;
  overflow: auto;
}
</style>
